<template>
    <div>
        <searchBox @handleSearch="handleQuery" @handleReset="resetQuery">
            <el-form :model="queryParams" ref="publicQueryForm" :inline="true" label-width="auto" label-position="left"
                :rules="shopProductRules">
                <el-form-item label="商品ID" prop="param.newIDs">
                    <el-input type="number" v-model.trim="queryParams.param.newIDs" placeholder="请输入" clearable
                        :min="1" />
                </el-form-item>
                <el-form-item label="商品名" prop="productName">
                    <el-input style="width: 200px" v-model.trim="queryParams.param.productName" placeholder="请输入"
                        clearable />
                </el-form-item>
                <el-form-item label="来源网站" prop="newCollectionSiteIds">
                    <el-select style="width: 200px" v-model="queryParams.param.newCollectionSiteIds" placeholder="请选择"
                        clearable @change="changeSite">
                        <el-option v-for="dict in host_type" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品分类" prop="personalRawCategoryIds">
                    <el-tree-select style="width: 200px" v-model="queryParams.param.personalRawCategoryIds"
                        :data="categoryOptions" :props="{ value: 'id', label: 'name', children: 'children' }"
                        value-key="id" placeholder="请选择" check-strictly clearable />
                </el-form-item>
                <el-form-item label="发布时间" prop="time">
                    <el-date-picker v-model="queryParams.param.newTime" type="datetimerange" start-placeholder="开始日期"
                        end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                        time-format="A hh:mm:ss" value-format="YYYY-MM-DD HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
            </el-form>
        </searchBox>

        <div
            style="display: flex;align-items: center;justify-content: space-between;border-bottom: 1px solid rgb(230, 230, 230);">
            <el-tabs v-model="queryParams.param.publishStatus" @tab-change="handleClick" type="card">
                <el-tab-pane label="全部" :name="null" />
                <el-tab-pane label="发布成功" name="Succeed" />
                <el-tab-pane label="发布失败" name="Failed" />
                <el-tab-pane label="发布中" name="Executing" />
            </el-tabs>
            <el-button type="primary" :disabled="!selectionId.length"
                @click="handleDelete(selectionId)">批量删除</el-button>
        </div>


        <el-table :data="productList" @selection-change="handleSelectionChange" ref="productListRef"
            style="height: calc(100vh - 340px)" v-loading="loading">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="商品ID" prop="personalProductId" width="100" />
            <el-table-column label="商品图" align="center" width="120">
                <template #default="scope">
                    <image-preview :src="scope.row.productMainImage" :width="75" :height="75" />
                </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="name">
                <template #default="scope">
                    <el-link :href="scope.row.rawUrl" target="_blank" :underline="false">{{
                        scope.row.productName
                        }}</el-link>
                    <div style="display: flex;flex-direction: column;">
                        <div class="mb8">
                            <el-button type="primary" plain size="small">
                                {{ scope.row.languageName }}
                            </el-button>
                            <el-link :href="scope.row.collectionSiteUrl" target="_blank" :underline="false"
                                style="margin-left: 10px;">{{
                                    scope.row.collectionSiteName
                                }}</el-link>
                        </div>
                        <div>
                            <el-tag type="primary" v-if="scope.row.newRawCategories?.length">
                                <el-text style="max-width: 150px;" truncated> {{
                                    scope.row.newRawCategories[0]?.name
                                }}</el-text>
                            </el-tag>

                            <el-tooltip effect="dark" placement="top-start">
                                <template #content>
                                    <el-space spacer=" " wrap>
                                        <div v-for="item in scope.row.newRawCategories" :key="item.id">
                                            <el-text style="color: #fff;" v-if="item.name">{{
                                                item.name }}</el-text>
                                        </div>
                                    </el-space>
                                </template>
                                <el-tag type="primary" style="margin-left: 10px;"
                                    v-if="scope.row.newRawCategories?.length > 1">More {{
                                        scope.row.newRawCategories?.length }}
                                </el-tag>
                            </el-tooltip>
                        </div>

                    </div>
                </template>
            </el-table-column>
            <el-table-column label="发布状态">
                <template #default="scope">
                    <el-button :type="scope.row.newEnumPublishStatus.code" plain
                        v-if="scope.row.enumPublishStatus != 'Failed'">{{ scope.row.newEnumPublishStatus.name
                        }}</el-button>
                    <el-tooltip effect="dark" placement="bottom">
                        <template #content>
                            <div style="max-width: 500px; white-space: pre-line;">
                                {{ scope.row.message }}
                            </div>
                        </template>
                        <el-button :type="scope.row.newEnumPublishStatus.code" plain
                            v-if="scope.row.enumPublishStatus == 'Failed'">{{
                                scope.row.newEnumPublishStatus.name
                            }}</el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column label="发布站点" prop="websiteName" />
            <el-table-column label="更新时间" prop="newEndDate" width="200px" align="center" />
            <el-table-column label="操作" align="center" width="150px" fixed="right">
                <template #default="scope">
                    <el-button link type="danger" @click="publicIncident(scope.row, 0)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <Pagination :total="total" :limit="queryParams.pageSize" :page="queryParams.pageNum"
            @pagination="handlePageChange">
        </Pagination>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
const { proxy } = getCurrentInstance();
const host_type = ref([]); //来源网站
const loading = ref(true)

const total = ref(0); // 总条数
const productList = ref([]); // 产品中心表格数据
const selectionId = ref([])//勾选的id

// 类别管理下拉框
const categoryOptions = ref([]);
// 查询参数
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    param: {
        productName: "", //产品名称
        collectionSiteIds: [], //来源网站
        personalRawCategoryIds: null, //商品分类
        startTime: null, //开始时间
        endTime: null, //结束时间
        productIds: null,

        newIDs: null,//,可以删除
        newCollectionSiteIds: null, //来源网站,可以删除
        publishStatus: null, //发布状态，Failed，Succeed，Executing
    },
});

const publicItem = ref({}); //公共赋值对象
onMounted(() => {
    getList();
    getLanguage(); //获取下拉数据
});


/** 查询产品中心列表 */
const getList = () => {
    product.publishrecord
        .publishrecordList({
            data: queryParams.value,
        })
        .then((res) => {
            total.value = res.total;
            loading.value = false
            if (res.data?.length) {
                res.data = res.data.map(code => {
                    return {
                        ...code,
                        newEnumPublishStatus: newEnumPublishStatus(code.enumPublishStatus),
                        newRawCategories: code.personalRawCategories || [],
                        newEndDate: proxy.DateTime(code.lastModified),
                    }
                })
            }
            productList.value = res.data;
            console.log(res.data);
        });
};
const handleClick = (e) => {
    if (queryParams.value.param.publishStatus === '0') return queryParams.value.param.publishStatus = null
    getList();
}
/** 搜索按钮操作 */
const handleQuery = () => {
    proxy.$refs["publicQueryForm"].validate((valid) => {
        if (!valid) return
        queryParams.value.param.endTime = null
        queryParams.value.param.startTime = null
        queryParams.value.param.id = null
        queryParams.value.param.collectionSiteIds = []
        if (queryParams.value.param.newTime?.length) {
            queryParams.value.param.startTime = proxy.convertTime(1, queryParams.value.param.newTime[0]);
            queryParams.value.param.endTime = proxy.convertTime(1, queryParams.value.param.newTime[1]);
        }
        if (queryParams.value.param.newIDs) {
            queryParams.value.param.productIds = Number(queryParams.value.param.newIDs)
        }

        if (queryParams.value.param.newCollectionSiteIds) {
            queryParams.value.param.collectionSiteIds = [queryParams.value.param.newCollectionSiteIds]
        }
        getList();
    })

};
const publicIncident = (row, index) => {
    publicItem.value = row
    handleDelete([row.id])
};
const handleDelete = (newIds) => {
    proxy.$modal.confirm('是否确认删除此数据？')
        .then(() => {
            product.publishrecord.publishrecordDeletebatch({
                data: { ids: newIds }
            }).then((res) => {
                if (res.code === 200) {
                    getList();
                    selectionId.value = [];
                }
            });
        })
}
const handleSelectionChange = (selection) => {// 多选框选中数据
    selectionId.value = selection.map((item) => item.id);
};
const changeSite = (e) => {
    queryParams.value.param.collectionSiteIds = []
    categoryOptions.value = []
    productSortList(e)
}

const getLanguage = () => {
    // 来源网站
    product.collectionsite
        .collectionsiteList({
            data: {
                pageNum: 1,
                pageSize: 999,
            },
        }).then((res) => {
            if (res.data?.length) {
                res.data = res.data.map((code) => {
                    return {
                        ...code,
                        label: code.name,
                        value: code.id,
                    };
                });
            }
            host_type.value = res.data;
        });
};
const productSortList = (e) => { // 采集商品分类
    product.rawcategory.rawcategoryList({
        data: {
            pageNum: 1,
            pageSize: 999,
            param: {
                languageId: 1,
                collectionSiteId: e
            },
        },
    }).then((response) => {
        categoryOptions.value = response.data;
    });
}
// 分页
const handlePageChange = (newPage) => {
    queryParams.value.pageNum = newPage.page;
    queryParams.value.pageSize = newPage.limit;
    getList();
};
const newEnumPublishStatus = (code) => {
    if (code === 'Succeed') {
        return {
            code: 'success',
            name: '发布成功',
        }
    } else if (code === 'Failed') {
        return {
            code: 'danger',
            name: '发布失败',
        }
    } else if (code === 'Executing') {
        return {
            code: 'warning',
            name: '发布中',
        }
    }
}
const shopProductRules = reactive({
    'param.newIDs': [
        {
            pattern: /^[1-9]\d*$/,
            message: "请正确输入ID",
            trigger: "blur",
        },
    ],
})
/** 重置按钮操作 */
const resetQuery = () => {
    queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        param: {
            productName: "", //产品名称
            collectionSiteIds: [], //来源网站
            personalRawCategoryIds: null, //商品分类
            startTime: null, //开始时间
            endTime: null, //结束时间
            productIds: null,

            newIDs: null,//,可以删除
            newCollectionSiteIds: null, //来源网站,可以删除
            publishStatus: '', //发布状态，Failed，Succeed，Executing
        },
    };
    getList();
};
</script>
<style lang="scss" scoped>
.Operation {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>